package controllers.admin;

import java.util.List;

import models.admin.Module;
import models.admin.Page;
import models.admin.PagePermission;
import models.admin.Permission;
import models.admin.Role;
import models.admin.User;
import play.mvc.With;
import controllers.BaseController;
import controllers.Check;
import controllers.Secure;

/**
 * @author rjanixz
 *
 */
@With(Secure.class)
public class Pages extends BaseController {

	@Check(value="ADD")
	public static void add() {
		List<Module> modules = Module.findAll();
		renderTemplate("/admin/pages/add.html",modules);
	}
	
	@Check(value="EDIT")
	public static void edit(Long id) {
		Page page = Page.findById(id);
		List<Module> modules = Module.findAll();
		List<Permission> permissions = Permission.findAll();
		renderTemplate("/admin/pages/edit.html",page,modules,permissions);
	}
	
	@Check(value="ADD")
	public static void save(Long parentId, Long moduleId, String name, String description) {
		
		Page page = new Page();
		Module module = Module.findById(moduleId);
		
//		Page parent = Page.findById(parentId);
//		if (parent != null) {
//			page.setParent(parent);
//		}
		
		page.setName(name);
		page.setDescription(description);
		page.setModule(module);
		page.save();
		
		redirect("/admin/pages/all");
	}
	
	@Check(value="EDIT")
	public static void update(Long pageId, Long parentId, Long moduleId, String name, String description) {
		Page page = Page.findById(pageId);
		
		
		Module module = Module.findById(moduleId);
		
//		Page parent = Page.findById(parentId);
//		if (parent != null) {
//			page.setParent(parent);
//		}
		
		page.setName(name);
		page.setDescription(description);
		page.setModule(module);
		page.save();
		
		renderTemplate("/admin/pages/all.html");
	}

	@Check(value="EDIT")
	public static void addDetail(Long pageId, Long permissionId) {
		Page page = Page.findById(pageId);
		Permission permission = Permission.findById(permissionId);
		PagePermission pagePermission = new PagePermission();
		pagePermission.setPage(page);
		pagePermission.setPermission(permission);
		pagePermission.save();
		redirect("/admin/pages/edit/"+pageId);
	}
	
	@Check(value="EDIT")
	public static void removeDetail(Long pagePermissionId) {
		PagePermission pagePermission = PagePermission.findById(pagePermissionId);
		pagePermission.delete();
		redirect("/admin/pages/edit/"+pagePermission.getPage().getId());
	}
}
